<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\bargain;

use app\api\model\Goods as GoodsModel;
use app\api\model\bargain\Task as TaskModel;
use app\api\model\bargain\TaskHelp as TaskHelpModel;
use app\api\service\User as UserService;
use app\common\model\bargain\Active as ActiveModel;
use cores\exception\BaseException;

/**
 * 砍价活动模型
 * Class Active
 * @package app\api\model\bargain
 */
class Active extends ActiveModel
{
    /**
     * 隐藏的字段
     * @var array
     */
    protected $hidden = [
        'peoples',
        'is_self_cut',
        'initial_sales',
        'actual_sales',
        'sort',
        'create_time',
        'update_time',
        'store_id',
        'is_delete',
    ];

    /**
     * 获取器：分享标题
     * @param $value
     * @return string
     */
    public function getShareTitleAttr($value): string
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * 获取器：砍价助力语
     * @param $value
     * @return string
     */
    public function getPromptWordsAttr($value): string
    {
        return htmlspecialchars_decode($value);
    }

    /**
     * 活动会场列表
     * @param array $param
     * @return mixed|\think\Paginator
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHallList(array $param = [])
    {
        return $this->getList(array_merge($param, ['status' => 1]));
    }

    /**
     * 获取砍价活动列表（根据活动id集）
     * @param array $activeIds
     * @param array $param
     * @return mixed|\think\Paginator
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getListByIds(array $activeIds, array $param = [])
    {
        return $this->getList(array_merge($param, ['activeIds' => $activeIds]));
    }

    /**
     * 获取砍价商品列表
     * @param array $param
     * @return mixed|\think\Paginator
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getList(array $param)
    {
        // 查询条件
        $params = $this->setQueryDefaultValue($param, [
            'activeIds' => [],
            'status' => 1,          // 商品状态
            'sortType' => 'all',    // 排序类型
            'sortPrice' => false,   // 价格排序 高低
            'listRows' => 15,       // 每页数量
        ]);
        // 查询模型
        $query = $this->getNewQuery();
        // 根据活动ID集
        if (is_array($params['activeIds']) && !empty($params['activeIds'])) {
            $query->orderRaw('field(active_id, ' . implode(',', $params['activeIds']) . ')');
            $query->where('active_id', 'in', $params['activeIds']);
        }
        // 排序规则
        if ($params['sortType'] === 'all') {
            $query->order(['sort' => 'asc']);
        } elseif ($params['sortType'] === 'sales') {
            $query->order(['active_sales' => 'desc']);
        } elseif ($params['sortType'] === 'price') {
            $query->order(['floor_price' => $params['sortPrice'] ? 'desc' : 'asc']);
        }
        // 砍价活动列表
        $list = $query->field(['*', '(actual_sales + initial_sales) as active_sales'])
            ->where('start_time', '<=', time())
            ->where('end_time', '>=', time())
            ->where('status', '=', $params['status'])
            ->where('is_delete', '=', 0)
            ->order(['sort' => 'asc'])
            ->paginate($params['listRows']);
        // 设置商品数据
        if (!$list->isEmpty()) {
            $list = $this->setGoodsListData($list, true, GoodsModel::getHidden(['goods_images']));
        }
        // 整理正在砍价的助力信息
        return $this->setHelpsData($list);
    }

    /**
     * 整理正在砍价的助力信息
     * @param $list
     * @return mixed
     */
    private function setHelpsData($list)
    {
        $model = new TaskHelpModel;
        foreach ($list as &$item) {
            $item['helpList'] = $model->getHelpListByActiveId($item['active_id']);
            $item['helpsCount'] = $model->getHelpCountByActiveId($item['active_id']);
        }
        return $list;
    }

    /**
     * 获取砍价活动详情
     * @param int $activeId
     * @return static|array|null
     * @throws BaseException
     */
    public function getDetail(int $activeId)
    {
        $model = static::detail($activeId);
        if (empty($model) || $model['is_delete'] || !$model['status']) {
            throwError('很抱歉，该砍价商品不存在或已下架');
        }
        return $model;
    }

    /**
     * 获取用户是否正在参与改砍价活动，如果已参与则返回task_id
     * @param int $activeId
     * @return bool|int
     * @throws BaseException
     */
    public function getWhetherPartake(int $activeId)
    {
        $userInfo = UserService::getCurrentLoginUser(false);
        return empty($userInfo) ? false : TaskModel::getHandByUser($activeId, $userInfo['user_id']);
    }

    /**
     * 累计活动销量(实际)
     * @return mixed
     */
    public function setIncSales()
    {
        return $this->setInc($this['active_id'], 'actual_sales', 1);
    }
}